#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    socket = new QTcpSocket(this);

    ui->sendBtn->setEnabled(false);
    ui->disconBtn->setEnabled(false);
    connect(socket,SIGNAL(connected()),this,SLOT(connectedSlot()));
    connect(socket,SIGNAL(readyRead()),this,SLOT(recvDataSlot()));
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_connectBtn_clicked()
{
    //连接服务器
    socket->connectToHost(QHostAddress("192.168.23.129"),8888);
    //只要连接成功，就会产生connected的信号
}
void Widget::connectedSlot()
{
    ui->connectBtn->setEnabled(false);
    ui->disconBtn->setEnabled(true);
    ui->sendBtn->setEnabled(true);
}
void Widget::recvDataSlot()
{
    ui->textBrowser->append("服务器"+QTime::currentTime().toString("hh:mm:ss"));
    char buf[1024] = {0};
    socket->read(buf,sizeof(buf));
    QString res = QString(buf);
    ui->textBrowser->append(res);
    QStringList res_list =  res.split(";");
    if(res_list.first() != "" && res_list.last().toInt() > 80){
        ui->label->setText(res_list.first()+",已识别");
    }


}

void Widget::on_sendBtn_clicked()
{
    //获取LineEdit上的文本信息
    QString str = ui->lineEdit->text();
    if(str.isEmpty())
    {
        return;
    }
    QByteArray arr;
    arr.append(str);
    socket->write(arr);
    ui->lineEdit->clear();
}

void Widget::on_disconBtn_clicked()
{
    socket->close();
    ui->connectBtn->setEnabled(true);
    ui->disconBtn->setEnabled(false);
    ui->sendBtn->setEnabled(false);
}
